package cn.bonoon.kernel.support.services.handler;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.support.entities.EntityMovable;
import cn.bonoon.kernel.support.entities.Persistable;

public class EditMovableHandler <E extends Persistable> implements EditHandler{
	
	private final String maxOrdinal;
	private final String updateOrdinal;
	
	public EditMovableHandler(String name){
		maxOrdinal = "select x.ordinal from " + name + " as x order by x.ordinal desc";
		updateOrdinal = "update " + name + " x set x.ordinal=(x.ordinal+1) where x.ordinal>=?";
	}
	
	/**
	 * <pre>
	 * 添加记录
	 * 1、此操作分为四种情况：ordinal为0 ；ordinal大于0 ;ordinal大于最大值；数据库为空
	 * 2、ordinal为0和大于最大值，先取出ordinal最大的记录，把此记录的ordinal + 1 作为新记录ordinal的值
	 * 3、ordinal大于0时，把新记录添加，然后取出大于新记录的所有数据，把其ordinal 加1 
	 * 4、数据库为空，则ordinal为1
	 * </pre>
	 */
	@Override
	public boolean insertHandler(EntityManager entityManager, OperateEvent event, Persistable entity) {
		EntityMovable em = (EntityMovable)entity;
		TypedQuery<Integer> tqSelect = entityManager.createQuery(maxOrdinal, Integer.class);
		List<Integer> list = tqSelect.setMaxResults(1).getResultList();
		Integer max = null;
		if(list.size() == 1){
			max = list.get(0);
		}
		if (null != max) {
			int ordinal = em.getOrdinal();
			if (ordinal == 0 || ordinal > max.intValue()){
				// ordinal = 0 或者大于最大值
				em.setOrdinal(max.intValue() + 1);
			}else{
				// ordinal > 0
				entityManager.createQuery(updateOrdinal).setParameter(1, ordinal).executeUpdate();
				/*
				 * 使用executeUpdate()更新数据库后，需要清理一下entityManager的缓存，否则无法取得最新的值
				 */
				entityManager.clear();
			}
		} else {
			// 空
			em.setOrdinal(1);
		}
		entityManager.persist(entity);
		return true;
	}
	
	@Override
	public boolean updateHandler(EntityManager entityManager, OperateEvent event, Persistable entity) {
		entityManager.merge(entity);
		return true;
	}
}
